package classifier;

import java.util.LinkedList;
import java.util.List;

import dao.InputFile;
import dao.OutputFile;
import distribution.Distribution;
import distribution.GaussianDistribution;
import dto.Sample;
import dxo.SampleParser;

public class GaussianClassifier implements Classifier {

	private Distribution model;
	
	@Override
	public void test(String file, String output) {
		InputFile fin = new InputFile();
		OutputFile fout = new OutputFile();
		fin.open(file);
		fout.open(output);
		
		fout.write("label 1 0\n");
		while(fin.hasNext()) {
			String line = fin.next();
			Sample sample = SampleParser.parse(line);
			double logProb = model.getLogProb(sample);
			int label = sample.getLabel();
			fout.write(label + " " + logProb + " 0\n");
		}
		fin.close();
		fout.close();
	}

	@Override
	public void train(String file, List<String> args) {
		int dim = Integer.parseInt(args.get(0));
		
		model = getDistribution();

		List<List<Sample>> positiveSampleList = loadPositiveSampleList(file);

		model.train(positiveSampleList, dim);
	}
	
	protected List<List<Sample>> loadPositiveSampleList(String filename) {
		List<List<Sample>> sampleList = new LinkedList<List<Sample>>();
		List<Sample> samples = new LinkedList<Sample>();
		
		InputFile fin = new InputFile();
		fin.open(filename);
		while(fin.hasNext()) {
			String line = fin.next();
			
			if(line.charAt(0) == '1') {
				Sample sample = SampleParser.parse(line);
				samples.add(sample);
			} else {
				if(!samples.isEmpty()) {
					sampleList.add(samples);
					samples = new LinkedList<Sample>();
				}
			}
		}
		fin.close();
		
		if(!samples.isEmpty()) {
			sampleList.add(samples);
		}

		return sampleList;
	}
	
	protected Distribution getDistribution() {
		return new GaussianDistribution();
	}
}
